<?php

class History extends CActiveRecord
{
	/**
	 * The followings are the available columns in table 'cat_history':
	 * @var integer $id
	 * @var integer $brand_id
	 * @var string $alias
	 * @var string $title
	 * @var string $image
	 * @var string $from
	 * @var string $until
	 * @var string $description
	 */
	public $RU_NAME = 'История марок';
	
	var $_image;
	
	var $_sizes = array(
		'orig',
		'small'=>array(42,42),
		'normal'=>array(120,120),
		'big'=>array(200,200),
	);
	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'cat_history';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('brand_id, title, alias', 'required'),
			array('brand_id, comments_count', 'numerical', 'integerOnly'=>true),
			array('alias', 'length', 'max'=>45),
			array('title, image', 'length', 'max'=>255),
			array('from, until, description, description_marked', 'safe'),
			array('from, until', 'default', 'setOnEmpty'=>'null'),
			
			array('_image', 'file', 'types'=>'jpg, gif, png', 'maxSize' => 10490000, 'allowEmpty'=>true),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, brand_id, alias, title, image, from, until, text_marked', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'brand' => array(self::BELONGS_TO, 'Brand', 'brand_id'),
			'comments'=>array(self::HAS_MANY, 'Comment', 'object_id', 'condition'=>'comments.type='.Lookup::ritem('CommentType',__CLASS__)),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'brand_id' => 'Бренд',
			'alias' => 'Псевдоним',
			'title' => 'Название',
			'image' => 'Картинка',
			'from' => 'С',
			'until' => 'По',
			'description' => 'Описание',
			'description_marked' => 'Описание',
			'comments_count' => 'Количество комментариев',
		
			'comments' => 'Комментарии',
			'_image' => 'Картинка',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);

		$criteria->compare('brand_id',$this->brand_id);

		$criteria->compare('alias',$this->alias,true);

		$criteria->compare('title',$this->title,true);

		$criteria->compare('image',$this->image,true);

		$criteria->compare('from',$this->from,true);

		$criteria->compare('until',$this->until,true);

		$criteria->compare('description',$this->description,true);

		return new CActiveDataProvider('History', array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>Yii::app()->params['linesPerPage'],
			),
		));
	}
	
	public function afterDelete(){
		# Проверка и очистка связей

		Comment::model()->deleteAll('object_id=:object_id and type='.Lookup::ritem('CommentType',__CLASS__),array(':object_id'=>$this->id));
		
		return parent::afterDelete();
	}
	
	public function beforeSave(){
		if($this->description) {
			Yii::import('ext.markdown.*');
			$md = new EMarkdown;
			$this->description_marked = $md->transform($this->description);
		}
		
		if(isset($_POST['delete_image']) && $_POST['delete_image'])
			$this->deleteImage();

		$this->uploadImage();
		
		return parent::beforeSave();
	}
	
	protected function uploadImage(){
		if($this->_image = CUploadedFile::getInstance($this,'_image')) {
			
			$filename = CString::strtolower($this->alias.'.'.$this->_image->extensionName);
			$path = Yii::getPathOfAlias( Yii::app()->params['paths']['history']['path'] ).DIRECTORY_SEPARATOR;

			$this->image = Image::addFile( $this->_image, $filename, $path, $this->_sizes, $this->title, $this->title);

		} elseif(empty($this->image)){
			$this->image = null;
		}
	}
	
	protected function deleteImage(){
		$this->image = null;
	}
	
}